﻿@inherits SsoSectionComponentBase

<MTextField Value="@Value.Password" TValue="string" ValueChanged="ValueChangeHandler" Class="mt-3" Label="@T("Password")" PrependInnerIcon="mdi-lock"
            Type="@(_showPwd ? "text" : "password")" Placeholder="@T("PasswordPlaceholder")" Rules="_pwdRules"
            AppendIcon="@(_showPwd ? "mdi-eye" : "mdi-eye-off")" OnAppendClick="()=>_showPwd = !_showPwd" Outlined>
</MTextField>
<MTextField @bind-Value="@Value.ConfirmPassword" Class="mt-3" Label="@T("ConfirmPassword")" PrependInnerIcon="mdi-lock"
            Type="@(_showPwd ? "text" : "password")" Placeholder="@T("ConfirmPasswordPlaceholder")" Rules="_confirmPwdRules"
            AppendIcon="@(_showPwd ? "mdi-eye" : "mdi-eye-off")" OnAppendClick="()=>_showPwd = !_showPwd" Outlined>
</MTextField>

@code {
    [Parameter]
    public RegisterInputModel Value { get; set; } = new();

    [Parameter]
    public EventCallback<RegisterInputModel> ValueChanged { get; set; }

    [Parameter]
    public bool Required { get; set; }

    bool _showPwd;

    private IList<Func<string, StringBoolean>> _pwdRules = new List<Func<string, StringBoolean>>();

    private IList<Func<string, StringBoolean>> _confirmPwdRules = new List<Func<string, StringBoolean>>();

    protected override Task OnParametersSetAsync()
    {
        if (!_pwdRules.Any())
        {
            _pwdRules.Add(value => Regex.Match(value, LoginOptions.PasswordRegular).Success ? true : T("PasswordRuleError"));
        }
        if (Required && _pwdRules.Count == 1)
        {
            _pwdRules.Add(value => !string.IsNullOrEmpty(value) ? true : T("PwdRequired"));
        }
        if (!_confirmPwdRules.Any())
        {
            _confirmPwdRules.Add(value => value.Equals(Value.Password) ? true : T("Password not equal ConfirmPassword"));
        }

        return base.OnParametersSetAsync();
    }

    void ValueChangeHandler(string value)
    {
        Value.Password = value;
    }
}
